package com.xunmall.wechat.util.wechat;

import com.xunmall.wechat.model.constant.WeChatLinkConstant;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * Created by wangyanjing on 2018/10/31.
 */
public class WeiXinCheckUtils {

    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        if (signature == null || timestamp == null || nonce == null) {
            return false;
        }
        String[] arr = {WeChatLinkConstant.TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder stringBuilder = new StringBuilder();
        for (String string : arr) {
            stringBuilder.append(string);
        }
        String temp = getSha1(stringBuilder.toString());
        return temp.equals(signature);
    }

    public static String getSha1(String string) {
        if (string == null || string.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(string.getBytes("UTF-8"));
            byte[] md = messageDigest.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception ex) {
            return null;
        }
    }

}
